package com.leador.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.leador.assist.DataQueueManager;
import com.leador.service.LBSTraceService;
import com.leador.socket.SocketMananger;
import com.leador.utils.ByteUtils;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by lhy on 2016/9/15.
 */
public class DBManger extends Thread{
    private Context context;
    private BaseHelper baseHelper = null;
    private SQLiteDatabase sqLiteDatabase = null;
    private SocketMananger socketMananger;
    private DataQueueManager dataQueueManager;
    public DBManger(LBSTraceService lbsTraceService){
        this.context = lbsTraceService.getContext();
        this.socketMananger = lbsTraceService.getSocketManager();
        dataQueueManager = DataQueueManager.getInstance();
    }

    public DBManger(){
        dataQueueManager = DataQueueManager.getInstance();
    }
    @Override
    public void run() {
        if(baseHelper == null){
            baseHelper = new BaseHelper(context);
        }

        if(sqLiteDatabase == null){
            sqLiteDatabase = baseHelper.getWritableDatabase();
        }

        String str1 = "select  count(*)  from trace_locationinfo";
        long l1;
        if ((l1 = baseHelper.selectSql(sqLiteDatabase, str1)) > 0L) {
            dataQueueManager.setDbHasValue(true);
        }else{
            dataQueueManager.setDbHasValue(false);
        }

        String[] arrayOfString = null;
        long l3 = 0L;
        String str2 = null;
        while ((socketMananger.socketConnect.socketIsConnect()) && (l1 > 0L)) {
            if (l1 > 720L) {
                l3 = 720L;
            } else {
                l3 = l1;
            }
            str2 = "select * from trace_locationinfo limit 0,?";
            arrayOfString = new String[] { String.valueOf(l3) };
            Cursor cursor;
            if ((cursor = baseHelper.b(sqLiteDatabase, str2, arrayOfString)) == null) {
                break;
            }
            while (cursor.moveToNext()){
                byte[] localObject = ByteUtils.stringToByte(cursor.getString(cursor.getColumnIndex("location_data")));
                dataQueueManager.bufferDataQueue.offer(localObject);
            }
            cursor.close();
            Object localObject = "delete  from  trace_locationinfo  where rowid in(select rowid from trace_locationinfo  limit 0,?)";
            baseHelper.deleteSql(sqLiteDatabase, (String)localObject, arrayOfString);
        }

        Log.e("db run",dataQueueManager.bufferDataQueue.size()+"");
        baseHelper.close();
        baseHelper = null;
        sqLiteDatabase.close();
        sqLiteDatabase = null;
    }


    public  void getSyncData(Context mcontext){
        try{
            if(baseHelper == null){
                baseHelper = new BaseHelper(mcontext);
            }

            if(sqLiteDatabase == null){
                sqLiteDatabase = baseHelper.getWritableDatabase();
            }
            String str1 = "select  count(*)  from trace_locationinfo";
            long count ;
            count =  baseHelper.selectSql(sqLiteDatabase, str1);
            String[] arrayOfString = null;
            String str2 = null;
            str2 = "select * from trace_locationinfo limit 0,?";
            arrayOfString = new String[] { String.valueOf(count) };
            Cursor cursor;
            if ((cursor = baseHelper.b(sqLiteDatabase, str2, arrayOfString)) == null) {
                return;
            }
            while (cursor.moveToNext()){
                byte[] localObject = ByteUtils.stringToByte(cursor.getString(cursor.getColumnIndex("location_data")));
                dataQueueManager.syncUpData.offer(localObject);
            }
            cursor.close();
            Object localObject = "delete  from  trace_locationinfo  where rowid in(select rowid from trace_locationinfo  limit 0,?)";
            baseHelper.deleteSql(sqLiteDatabase, (String)localObject, arrayOfString);
            Log.e("db run",dataQueueManager.syncUpData.size()+"");
            baseHelper.close();
            baseHelper = null;
            sqLiteDatabase.close();
            sqLiteDatabase = null;
        }catch (Exception e){

        }
    };

    public void insert(Context mcontext,Deque deque){
        if(deque == null){
            return;
        }
        try{
            if (baseHelper == null) {
                baseHelper = new BaseHelper(mcontext);
            }
            if (sqLiteDatabase == null) {
                sqLiteDatabase = baseHelper.getWritableDatabase();
            }
            LinkedList list = new LinkedList();
            if(deque.size()>0){
                list.addAll(deque);
            }
            if ((list != null) && (list.size() > 0)) {
                inserDb(list);
            }
            return;
        }catch (Exception e){

        }
    }

    public  void insert() {
        try {
            if (baseHelper == null) {
                baseHelper = new BaseHelper(context);
            }
            if (sqLiteDatabase == null) {
                sqLiteDatabase = baseHelper.getWritableDatabase();
            }
            LinkedList list = new LinkedList();
            Deque tempDataQueue = dataQueueManager.getTempDataQueue();
            if(tempDataQueue != null && tempDataQueue.size() > 0){
                list.addAll(dataQueueManager.tempDataQueue);
                dataQueueManager.tempDataQueue.removeAll(list);
            }

            Deque bufferDataQueue = dataQueueManager.getBufferDataQueue();
            if(bufferDataQueue != null && bufferDataQueue.size() > 0){
                list.addAll(dataQueueManager.bufferDataQueue);
                dataQueueManager.bufferDataQueue.removeAll(list);
            }

            Deque realtimeDataQueue = dataQueueManager.getRealtimeDataQueue();
            if(realtimeDataQueue != null && realtimeDataQueue.size() > 0){
                list.addAll(dataQueueManager.realtimeDataQueue);
                dataQueueManager.realtimeDataQueue.removeAll(list);
            }

            if ((list != null) && (list.size() > 0)) {
                inserDb(list);
            }
            return;
        }
        catch (Exception localException) {}
    }

    private  void inserDb(Queue queue) {
        Object localObject = null;
        sqLiteDatabase.beginTransaction();
        try {
            Iterator iterator = queue.iterator();
            while (iterator.hasNext()) {
                localObject = (byte[])iterator.next();
                localObject = "insert into trace_locationinfo(location_data)  values('" + ByteUtils.btteToString((byte[])localObject) + "')";
                baseHelper.a(sqLiteDatabase, (String)localObject);
            }
            sqLiteDatabase.setTransactionSuccessful();
            sqLiteDatabase.endTransaction();
            sqLiteDatabase.close();
            sqLiteDatabase = null;
            baseHelper.close();
            baseHelper = null;
            return;
        } catch (Exception paramQueue) {
            sqLiteDatabase.endTransaction();
            sqLiteDatabase.close();
            sqLiteDatabase = null;
            baseHelper.close();
            baseHelper = null;
            return;
        }
        finally {
            sqLiteDatabase.endTransaction();
            sqLiteDatabase.close();
            sqLiteDatabase = null;
            baseHelper.close();
            baseHelper = null;
        }
    }
}
